package com.puman.watchtrade.fragment.home;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.BreakIterator;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.mob.tools.utils.UIHandler;
import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.fragment.home.adapter.GoodsParmListViewAdapter;
import com.puman.watchtrade.fragment.home.adapter.GoodsShowImageListViewAdapter;
import com.puman.watchtrade.fragment.home.adapter.PriceGridViewAdapter;
import com.puman.watchtrade.fragment.home.httphandler.HomeHttpHandler;
import com.puman.watchtrade.fragment.home.model.GoodsDetails;
import com.puman.watchtrade.fragment.info.adpter.ImgAdapter;
import com.puman.watchtrade.fragment.info.adpter.MyGallery;
import com.puman.watchtrade.fragment.set.LoginFragment;
import com.puman.watchtrade.util.BaseFragment;
import com.puman.watchtrade.util.Config;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.LoadingProgressDialog;
import com.puman.watchtrade.util.expandableLayout.ExpandableLayout;
import com.puman.watchtrade.util.garlary.CirclePageIndicator;
import com.puman.watchtrade.util.garlary.ScreenSlidePagerAdapter;

/*
 */
@SuppressLint({ "ValidFragment", "NewApi" })
public class GoodsDetailFragment extends BaseFragment implements
		OnClickListener, PlatformActionListener, Callback {
	private View mView;
	private View listView;

	/*
	 * init UI
	 */
	private MyGallery gallery = null;
	private LinearLayout ll_focus_indicator_container = null;
	private GridView gridView;
	private PriceGridViewAdapter adapter;
	ListView goodsShowListView;
	ListView goodsParam;
	GoodsShowImageListViewAdapter goodsShowImageListViewAdapter;
	GoodsParmListViewAdapter goodsParmListViewAdapter;
	TextView endtimeInfo;
	TextView goodsName;
	TextView currentPrice;
	TextView offerRecord;// 出价记录
	TextView joinNo;
	TextView corwdNo;
	TextView priceInfo;
	RelativeLayout priceRecordLayout;
	ExpandableLayout expandableLayout1;
	ExpandableLayout expandableLayout2;
	RelativeLayout joinLayout;
	TextView joinNoBidded;// 已经参与报价
	FrameLayout biddinglayout;
	TextView biddInfo;
	TextView biddStatusInfo;
	/*
	 * init variable
	 */
	private ArrayList<String> imgList;
	private ArrayList<String> titleList;
	private ArrayList<ImageView> portImg;
	private Activity mContext;
	public static final int DETAIL_SUC = 0x1;
	public static final int DETAIL_FAIL = 0x2;
	private static final int CODE_SUC = 0x3;
	private static final int CODE_FAIL = 0x4;
	public static final int SUB_SUC = 0x5;
	public static final int SUB_FAIL = 0x6;
	public static final int LOAD_OVER = 0x7;
	HomeHttpHandler homeHttpHandler = new HomeHttpHandler();
	private DataResult dataResult = new DataResult();
	private DataResult dataResultForTake = new DataResult();
	GoodsDetails goodsDetails = new GoodsDetails();
	private String goodsNo = "";
	private String price = "";// 报价出价
	// private boolean isBidded = false;// 是否已经参与报价
	String code = "";
	private String biddingStatus = "";// 1:报价中 2：已结束3:审核中
	VarietiesListFragment varietiesListFragment;
	private boolean needSetPage = false;
	ScrollView scrollView;
//	private String topTitleStr = "会麦奢侈品金融";
	private int showImgHeight = 0;
	private int topImgHeight = 0;
	private boolean biddingSucRefrash = false;
	private String imgUrl = "";
	private String title = "";
	
	public GoodsDetailFragment() {
		// TODO Auto-generated constructor stub
	}

	public GoodsDetailFragment(String goodsNo, String biddingStatus) {
		this.biddingStatus = biddingStatus;
		this.goodsNo = goodsNo;
		needSetPage = false;
	}

	public GoodsDetailFragment(String goodsNo, String biddingStatus,
			VarietiesListFragment varietiesListFragment) {
		this.biddingStatus = biddingStatus;
		this.goodsNo = goodsNo;
		this.varietiesListFragment = varietiesListFragment;
//		this.imgUrl = imgUrl;
//		this.title = title;
		needSetPage = true;
		// Log.i("curry", "GoodsDetailFragment   end");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	// ****************************************

	private ViewPager pager;
	private CirclePageIndicator mPageIndicator;

	// ****************************************
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		mView = inflater.inflate(R.layout.goodsdetail_layout, container, false);
		initView();
		getData();
		return mView;
	}

	private void initView() {

		mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(this);
		mView.findViewById(R.id.share_layout).setOnClickListener(this);

		scrollView = (ScrollView) mView.findViewById(R.id.scrollview);
		ll_focus_indicator_container = (LinearLayout) mView
				.findViewById(R.id.ll_focus_indicator_container);
		gridView = (GridView) mView.findViewById(R.id.grid);

		endtimeInfo = (TextView) mView.findViewById(R.id.goods_detail_timeshow);
		goodsName = (TextView) mView.findViewById(R.id.goods_detail_name);
		currentPrice = (TextView) mView.findViewById(R.id.goods_detail_price);
		offerRecord = (TextView) mView
				.findViewById(R.id.good_detail_price_record_info_record);
		joinNo = (TextView) mView
				.findViewById(R.id.good_detail_price_record_join);
		corwdNo = (TextView) mView
				.findViewById(R.id.good_detail_price_record_crowd);

		expandableLayout1 = (ExpandableLayout) mView.findViewById(R.id.first);
		expandableLayout2 = (ExpandableLayout) mView.findViewById(R.id.second);
		expandableLayout1.show();
		expandableLayout2.show();

		priceInfo = (TextView) mView.findViewById(R.id.goods_detail_price_info);
		priceRecordLayout = (RelativeLayout) mView
				.findViewById(R.id.goods_detail_price_record);
		joinLayout = (RelativeLayout) mView
				.findViewById(R.id.good_detail_price_joinpeople_info1);
		joinLayout.setVisibility(View.INVISIBLE);
		joinNoBidded = (TextView) mView
				.findViewById(R.id.good_detail_price_record_join1);
		biddinglayout = (FrameLayout) mView.findViewById(R.id.bidding_layout);

		// code = creatRamdCode();
		biddInfo = (TextView) mView.findViewById(R.id.operation_bidd_info);
		biddStatusInfo = (TextView) mView.findViewById(R.id.bidding_status);

		if (biddingStatus.equals("1")) {
			if (GlobalData.userInfo != null
					&& GlobalData.userInfo.getType().equals("0")) {
				biddInfo.setText("请先认证");
				biddinglayout.setBackgroundColor(MainActivity.getInstant()
						.getResources().getColor(R.color.diliverLine));
			} else {
				biddInfo.setText("参与报价");
				biddStatusInfo.setText("报价进行中");
				biddinglayout.setBackgroundColor(MainActivity.getInstant()
						.getResources().getColor(R.color.themeColor));
			}
			if (GlobalData.userInfo == null) {
				priceInfo.setVisibility(View.GONE);
				currentPrice.setVisibility(View.GONE);
			} else {

			}
			priceInfo.setText("您的出价");
			joinLayout.setVisibility(View.VISIBLE);
			priceRecordLayout.setVisibility(View.GONE);
			biddinglayout.setOnClickListener(this);

		} else if (biddingStatus.equals("2")) {
			biddInfo.setText("报价结束");
			biddStatusInfo.setText("报价已结束");
			priceInfo.setText("最高出价");
			joinLayout.setVisibility(View.GONE);
			priceRecordLayout.setVisibility(View.VISIBLE);
			biddinglayout.setBackgroundColor(MainActivity.getInstant()
					.getResources().getColor(R.color.diliverLine));
			biddinglayout.setOnClickListener(null);
		} else {
			biddInfo.setText("审核中");
			biddStatusInfo.setText("报价已结束");
			priceInfo.setText("最高出价");
			joinLayout.setVisibility(View.GONE);
			priceRecordLayout.setVisibility(View.VISIBLE);
			biddinglayout.setBackgroundColor(MainActivity.getInstant()
					.getResources().getColor(R.color.diliverLine));
			biddinglayout.setOnClickListener(null);
		}
		/*
		 * 详情图片
		 */
		showImgHeight = (int) (GlobalData.screenWidth * ((float) 400 / (float) 640));
		// 顶部轮播图高度
		topImgHeight = (int) (GlobalData.screenWidth * ((float) 450 / (float) 640));

		loadAnimation();
	}

	private void loadAnimation() {
		AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
		// 设置动画执行的时间
		alphaAnimation.setDuration(1500);
		AnimationSet animationalpha = new AnimationSet(true);

		animationalpha.addAnimation(alphaAnimation);
		mView.findViewById(R.id.scrollview).startAnimation(animationalpha);
		// mView.findViewById(R.id.scrollview).startAnimation(MainActivity.animationalpha);
	}

	private LoadingProgressDialog mProgress = null;

	private void getData() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(goodsRunnable);
	}

	/*
	 * 获取 商品详情
	 */
	Runnable goodsRunnable = new Runnable() {
		@Override
		public void run() {
			int what = DETAIL_FAIL;
			dataResult = homeHttpHandler.GoodsDetailInfo(goodsNo);
			if (dataResult.flag) {
				what = DETAIL_SUC;
			}
			sendMessage(what);
		}
	};

	/*
	 * 确认报价
	 */
	private void takeIn() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(takeRunnable);
	}

	/*
	 * 获取 商品详情
	 */
	Runnable takeRunnable = new Runnable() {
		@Override
		public void run() {
			int what = SUB_FAIL;
			dataResultForTake = null;
			dataResultForTake = new DataResult();
			dataResultForTake = homeHttpHandler.takeIn(goodsNo, price);
			if (dataResult.flag) {
				what = SUB_SUC;
			}
			sendMessage(what);
		}
	};

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Gjfun.stopProgressDialog(mProgress);
			switch (msg.what) {
			case DETAIL_SUC:
				goodsDetails.goodsDetailList.clear();
				for (int i = 0; i < ((GoodsDetails) (dataResult.object)).goodsDetailList
						.size(); i++) {
					goodsDetails.goodsDetailList
							.add(((GoodsDetails) (dataResult.object)).goodsDetailList
									.get(i));
				}
				// Log.i("curry", goodsDetails.goodsDetailList.get(location));
				// if (GlobalData.userInfo != null) {
				// for (int j = 0; j <
				// goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
				// .size(); j++) {
				// if
				// (goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
				// .get(j).getUseNo()
				// .equals(GlobalData.userInfo.getUserNo())) {
				// isBidded = true;
				// break;
				// }
				// }
				// }
				if (!biddingSucRefrash) {
					setTopImg();
					setShowImg();
				}
				code = creatRamdCode();
				setOther();
				sendMessage(LOAD_OVER);
				break;
			case LOAD_OVER:
				scrollView.scrollTo(0, 0);
				break;
			case DETAIL_FAIL:
				break;
			case CODE_SUC:
				if (dataResultForTake.msg.equals("2")
						|| dataResultForTake.msg.equals("4")) {
					Toast.makeText(MainActivity.getInstant(),
							"" + dataResultForTake.msg, Toast.LENGTH_SHORT)
							.show();
				} else if (dataResultForTake.msg.equals("5")) {
					biddInfo.setText("审核中");
					biddinglayout.setBackgroundColor(MainActivity.getInstant()
							.getResources().getColor(R.color.diliverLine));
				} else {
					// Log.i("curry", "msg:" + dataResultForTake.msg);
				}
				Drawable drawable = new BitmapDrawable(bitmap);
				codeImg.setBackground(drawable);
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
					codeImg.setBackground(drawable);
				} else {
					codeImg.setBackgroundDrawable(drawable);
				}
				break;
			case CODE_FAIL:
				break;
			case SUB_SUC:
				biddingSucRefrash = true;
				getData();
				break;
			case SUB_FAIL:
				biddingSucRefrash = false;
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.share_layout:
			// MainActivity.getInstant().oks.show(getActivity());
			showShare();
			break;
		case R.id.main_left_imgbtn:
			if (needSetPage) {
				if (biddingStatus.equals("2")) {
					varietiesListFragment.currIndex = 0;
				} else {
					varietiesListFragment.currIndex = 0;
				}
			}
			MainActivity.getInstant().fragmentManager.popBackStack();
			break;
		case R.id.bidding_layout:

			if (GlobalData.userInfo == null) {
				Toast.makeText(MainActivity.getInstant(), "请先登录",
						Toast.LENGTH_SHORT).show();
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				LoginFragment loginFragment = new LoginFragment();
				transaction.replace(R.id.main_non_bottom, loginFragment);
				transaction.addToBackStack(null);
				transaction.commit();
				break;
			}
			if (GlobalData.userInfo.getType().equals("0")) {
				Toast.makeText(MainActivity.getInstant(), "请先成为认证会员",
						Toast.LENGTH_SHORT).show();
			} else {
				joinBidding();
			}

			break;
		default:
			break;
		}

	}

	/*
	 * 设置水平gridview
	 */
	private void setGridView() {
		offerRecord.setText("("
				+ goodsDetails.goodsDetailList.get(0).comRecords.getComCount()
				+ ")");
		joinNo.setText(goodsDetails.goodsDetailList.get(0).getJoinCount());
		corwdNo.setText(goodsDetails.goodsDetailList.get(0).getVistoerCount());
		int size = goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
				.size();
		// int size = 10;
		int length = 120;

		DisplayMetrics dm = new DisplayMetrics();
		MainActivity.getInstant().getWindowManager().getDefaultDisplay()
				.getMetrics(dm);
		float density = dm.density;
		int gridviewWidth = (int) (size * (length + 4) * density);
		int itemWidth = (int) (length * density);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
		gridView.setLayoutParams(params); // 重点
		gridView.setColumnWidth(itemWidth); // 重点
		gridView.setHorizontalSpacing(5); // 间距
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setNumColumns(size); // 重点

		adapter = new PriceGridViewAdapter(MainActivity.getInstant()
				.getApplicationContext(),
				goodsDetails.goodsDetailList.get(0).comRecords);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// sellImgs.sellimgList.get(position).isSelect =
				// !sellImgs.sellimgList.get(position).isSelect;
				adapter.notifyDataSetChanged();
			}
		});
	}

	private void setOther() {
		endtimeInfo.setText(goodsDetails.goodsDetailList.get(0).getEnd_time());
		goodsName.setText(goodsDetails.goodsDetailList.get(0).getName());
		title = goodsDetails.goodsDetailList.get(0).getName();

		if (biddingStatus.equals("1")) {
			// Log.i("curry", "isBidded：" + isBidded);
			// if (isBidded) {
			//
			// for (int j = 0; j <
			// goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
			// .size(); j++) {
			// if (goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
			// .get(j).getUseNo()
			// .equals(GlobalData.userInfo.getUserNo())) {
			// currentPrice
			// .setText("￥"
			// + goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
			// .get(j).getPrice());
			// break;
			// }
			// }
			// } else {
			if (!goodsDetails.goodsDetailList.get(0).getMyPrice().equals("0")) {
				priceInfo.setText("您的出价");
				biddInfo.setText("修改报价");
				currentPrice.setText("￥"
						+ goodsDetails.goodsDetailList.get(0).getMyPrice());
			} else {
				priceInfo.setText("您的出价");
				currentPrice.setText("￥" + "0");
				joinLayout.setVisibility(View.VISIBLE);
				joinNoBidded.setText(goodsDetails.goodsDetailList.get(0)
						.getJoinCount());
			}

			// }
		} else {
			priceInfo.setText("最高出价");
			if (goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
					.size() > 0) {
				currentPrice
						.setText("￥"
								+ goodsDetails.goodsDetailList.get(0).comRecords.comRecordList
										.get(0).getPrice());
			} else {
				currentPrice.setText("￥0");
			}

		}
		setGridView();

	}

	private void setShowImg() {
		// 商品展示
		goodsShowListView = (ListView) mView.findViewById(R.id.listview_list);
		// Log.i("curry",
		// "img size:"+goodsDetails.goodsDetailList.get(0).goodsShowImg.size());
		goodsShowImageListViewAdapter = new GoodsShowImageListViewAdapter(
				getActivity(),
				goodsDetails.goodsDetailList.get(0).goodsShowImg);
		goodsShowListView.setAdapter(goodsShowImageListViewAdapter);
		goodsShowListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				String[] imgStrings = new String[goodsDetails.goodsDetailList
						.get(0).goodsShowImg.size()];
				for (int i = 0; i < goodsDetails.goodsDetailList.get(0).goodsShowImg
						.size(); i++) {
					imgStrings[i] = goodsDetails.goodsDetailList.get(0).goodsShowImg
							.get(i);
				}
				imageBrower(position, imgStrings);
			}
		});
		// 商品参数
		goodsParam = (ListView) mView.findViewById(R.id.listview);
		goodsParmListViewAdapter = new GoodsParmListViewAdapter(getActivity(),
				goodsDetails.goodsDetailList.get(0).goodsParm);
		goodsParam.setAdapter(goodsParmListViewAdapter);
		goodsParam.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if (goodsDetails.goodsDetailList.get(0).goodsParm.get(position)
						.length() >= 20) {
					Toast.makeText(
							MainActivity.getInstant(),
							goodsDetails.goodsDetailList.get(0).goodsParm
									.get(position), Toast.LENGTH_LONG).show();
				}
			}
		});

		LayoutParams layoutParams = (LayoutParams) goodsShowListView
				.getLayoutParams();
		// Log.i("curry",
		// "showimg size:"+goodsDetails.goodsDetailList.get(0).goodsShowImg.size());
		// Log.i("curry", "height:"+layoutParams.height);
		layoutParams.height = showImgHeight
				* goodsDetails.goodsDetailList.get(0).goodsShowImg.size();
		// Log.i("curry", "height:"+layoutParams.height);
		goodsShowListView.setLayoutParams(layoutParams);
		LayoutParams layoutParams1 = (LayoutParams) goodsParam
				.getLayoutParams();
		// Log.i("curry", "height:"+layoutParams1.height);
		layoutParams1.height = layoutParams1.height
				* (goodsDetails.goodsDetailList.get(0).goodsParm.size());
		// Log.i("curry", "height:"+layoutParams1.height);
		goodsParam.setLayoutParams(layoutParams1);
		goodsShowImageListViewAdapter.notifyDataSetChanged();
		goodsParmListViewAdapter.notifyDataSetChanged();
	}

	private void imageBrower(int position, String[] urls) {
		Intent intent = new Intent(mContext, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		mContext.startActivity(intent);
	}

	/**
	 * 存储上一个选择项的Index
	 */
	private int preSelImgIndex = 0;

	private void setTopImg() {
		imgList = new ArrayList<String>();
		// titleList = new ArrayList<String>();
		for (int i = 0; i < goodsDetails.goodsDetailList.get(0).goodsTopImg
				.size(); i++) {
			imgList.add(goodsDetails.goodsDetailList.get(0).goodsTopImg.get(i));
			// titleList.add(infoImgs.imgList.get(i).getTitle());
		}
		imgUrl = goodsDetails.goodsDetailList.get(0).goodsTopImg.get(0);
		
		InitFocusIndicatorContainer();
		gallery = (MyGallery) mView.findViewById(R.id.gallery);
		int height = topImgHeight;
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				gallery.getLayoutParams().width, height);
		gallery.setLayoutParams(layoutParams);
		gallery.setAdapter(new ImgAdapter(getActivity(), imgList, getActivity()));
		gallery.setFocusable(true);
		gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int selIndex,
					long arg3) {
				// TODO Auto-generated method stub
				selIndex = selIndex % imgList.size();
				String[] imgStrings = new String[imgList.size()];
				         				for (int i = 0; i < imgList.size(); i++) {
				         					imgStrings[i] = imgList.get(i);
				         				}
				         				imageBrower(selIndex, imgStrings);
//				Toast.makeText(MainActivity.getInstant(), "selIndex:"+selIndex, Toast.LENGTH_SHORT).show();
			}
		});
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int selIndex, long arg3) {
				selIndex = selIndex % imgList.size();
				// 修改上一次选中项的背景
				portImg.get(preSelImgIndex).setImageResource(
						R.drawable.detail_dot_unselect);
				// 修改当前选中项的背景
				portImg.get(selIndex).setImageResource(
						R.drawable.detail_dot_select);
				// if (titleList.get(selIndex).length() > 15) {
				// topImgTitle.setText(titleList.get(selIndex).substring(0,
				// 15)+"...");
				// }else {
				// topImgTitle.setText(titleList.get(selIndex));
				// }
				preSelImgIndex = selIndex;
//				Toast.makeText(MainActivity.getInstant(), "selIndex:"+selIndex, Toast.LENGTH_SHORT).show();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

	}

	private void InitFocusIndicatorContainer() {
		portImg = new ArrayList<ImageView>();
		for (int i = 0; i < imgList.size(); i++) {
			ImageView localImageView = new ImageView(MainActivity.getInstant());
			localImageView.setId(i);
			ImageView.ScaleType localScaleType = ImageView.ScaleType.FIT_XY;
			localImageView.setScaleType(localScaleType);
			LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(
					40, 40);
			localImageView.setLayoutParams(localLayoutParams);
			localImageView.setPadding(5, 5, 5, 5);
			localImageView.setImageResource(R.drawable.detail_dot_unselect);
			portImg.add(localImageView);
			this.ll_focus_indicator_container.addView(localImageView);
		}
	}

	
	private ImageView codeImg;
	private AlertDialog alertDialog;
	public void joinBidding() {
		alertDialog = new AlertDialog.Builder(MainActivity.getInstant())
				.create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.join_bidding_dialog);
		window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// ��������n
		TextView sureBtn = (TextView) window.findViewById(R.id.sure_btn);
		TextView cancleBtn = (TextView) window.findViewById(R.id.cancle_btn);
		window.findViewById(R.id.validate_code).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
					}
				});
		codeImg = (ImageView) window.findViewById(R.id.validate_code);
		final TextView cash = (TextView) window.findViewById(R.id.custome_cash);
		final TextView Totalcash = (TextView) window
				.findViewById(R.id.added_poundage);
		TextView advicePrice = (TextView) window.findViewById(R.id.advice_price);
		advicePrice.setText("心理底价:￥"+goodsDetails.goodsDetailList.get(0).getPsychologicalPrice());
		cash.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.length() != 0) {
					double poundage = Double.parseDouble(GlobalData.userInfo
							.getPoundage()) / 100;
					double cashnu = Double.parseDouble(cash.getText()
							.toString());
					double total = cashnu
							* (Double.parseDouble("1") + poundage);
					
					String showTotal = priceValidate(total);

					Totalcash.setText("您的实际支付:￥" + showTotal + " ("
							+ GlobalData.userInfo.getPoundage() + "%佣金)");
				} else {
					Totalcash.setText("");
				}

				// 您的实际支付:￥1118898 (5%佣金)
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		final TextView useCode = (TextView) window
				.findViewById(R.id.customer_code);

		MainActivity.getInstant().cachedThreadPoolMinPriority
				.execute(CodeRunnable);
		codeImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				code = creatRamdCode();
				MainActivity.getInstant().cachedThreadPoolMinPriority
						.execute(CodeRunnable);

			}
		});
		sureBtn.setBackgroundColor(MainActivity.getInstant().getResources()
				.getColor(R.color.themeColor));
		sureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Double showprice = Double.parseDouble(cash.getText().toString());
				if (showprice < 100) {
					Toast.makeText(MainActivity.getInstant(), "最低报价不得低于100元",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (useCode.getText().toString().equals(code)) {
					alertDialog.dismiss();
					price = cash.getText().toString();
//					price = showTotal;
					takeIn();
				} else {
					Toast.makeText(MainActivity.getInstant(), "验证码不正确",
							Toast.LENGTH_SHORT).show();
				}
				InputMethodManager imm = (InputMethodManager) v.getContext()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),
							0);
				}
			}
		});
		cancleBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) v.getContext()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),
							0);
				}
				alertDialog.dismiss();
			}
		});
	}

	/*
	 * 价格是否合理
	 */
	private String priceValidate(double price) {
		DecimalFormat df = new DecimalFormat("###.00");
		return df.format(price) + "";
	}

	Bitmap bitmap = null;
	Runnable CodeRunnable = new Runnable() {

		@Override
		public void run() {
			String path = Config.valCode + code;
			try {
				URL url = new URL(path); // path图片的网络地址
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();
				if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					bitmap = BitmapFactory.decodeStream(httpURLConnection
							.getInputStream());
					// System.out.println("加载网络图片完成");
					sendMessage(CODE_SUC);
				} else {
					System.out.println("加载网络图片失败");
					sendMessage(CODE_FAIL);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	};

	/*
	 * 生成四位随机
	 */
	private String creatRamdCode() {
		String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
				"8", "9", "1"};
		List list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(5, 9);
		return result;
	}

	private String infoUrl = "http://www.huimaionline.com";
	String customerUrl = "";//跳转app
	private void showShare() {
		ShareSDK.initSDK(MainActivity.getInstant());
		OnekeyShare oks = new OnekeyShare();
		// oks.disableSSOWhenAuthorize();
		oks.setTitle(getString(R.string.share));
//		oks.setTitleUrl(infoUrl);
		String userNo = "";
		if (GlobalData.userInfo != null) {
			userNo = GlobalData.userInfo.getUserNo();
		}
		
//		oks.setTitleUrl("http://www.huimaionline.com");
		 customerUrl = "http://hmapi.puman.com/html/openapp.html?" +
				"urlschemes=watchtrade://goodsDetil?goodsNo="+goodsNo+
				"&inWitch="+biddingStatus+
						"&datetime="+System.currentTimeMillis(); //跳转app
		oks.setTitleUrl(customerUrl);
//		oks.setTitleUrl("watchtrade://detail?"+
//						"goodsNo="+goodsNo+"&userNo="+userNo);
//		Log.i("curry", "url"+"watchtrade://goodsdetail/get/detail?"+
//				"goodsNo="+goodsNo+"&userNo="+userNo);
//		oks.setTitleUrl("http://hmapi.puman.com/html/openapp.html?" +
//					"urlschemes=watchtrade://detail?goodsNo=("+goodsNo+"goodsNo)" +
//							"&inWitch=("+biddingStatus+")&datetime="+System.currentTimeMillis()
//				);
		
		oks.setText(title);
		oks.setUrl(infoUrl);
		oks.setImageUrl(imgUrl.replace(" ", ""));
		oks.setComment("...");
		oks.setSite(getString(R.string.app_name));
		oks.setSiteUrl(infoUrl);
		oks.setCallback(this);
		// 此处为本demo关键为一键分享折子定义分享回调函数 shareContentCustomuzeCallback
		// 自定义平台可以通过判断不同的平台来实现不同平台间的不同操作
	
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
			// 自定义分享的回调想要函数
			@Override
			public void onShare(Platform platform,
					cn.sharesdk.framework.Platform.ShareParams paramsToShare) {
				// 点击微信好友
				if ("Wechat".equals(platform.getName())) {
					paramsToShare.setTitle("会麦奢侈品金融");
					paramsToShare.setText(title);
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setImageUrl(imgUrl.replace(" ", ""));
//					paramsToShare.setUrl(infoUrl);
					paramsToShare.setUrl(customerUrl);
				}
				
//				Log.i("curry", "platform:"+platform.getName());
				if (WechatMoments.NAME.equals(platform.getName())) {
					paramsToShare.setTitle("会麦奢侈品金融");
					paramsToShare.setText(title);
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setImageUrl(imgUrl.replace(" ", ""));
//					paramsToShare.setUrl(infoUrl);
					paramsToShare.setUrl(customerUrl);
				}
				// 点击新浪微博
				if (SinaWeibo.NAME.equals(platform.getName())) {
					// 限制微博分享的文字不能超过20
					if (paramsToShare.getText().length() > 20) {
						Toast.makeText(MainActivity.getInstant(),
								"分享长度不能超过20个字", Toast.LENGTH_SHORT).show();
					}
					paramsToShare.setTitle("会麦奢侈品金融");
					paramsToShare.setText(title + " " + infoUrl);
					paramsToShare.setImageUrl(imgUrl.replace(" ", ""));
				}
				// 点击除了QQ以外的平台
				if (!"QQ".equals(platform.getName())) {
					Log.i("", "点击了QQ以外的平台");
				}
			}
		});
		// 启动分享GUI
		oks.show(MainActivity.getInstant());
	}

	@Override
	public void onCancel(Platform platf, int arg1) {
		Log.i("", "onCancel");
		if (arg1 == Platform.ACTION_SHARE) {
			UIHandler.sendEmptyMessage(SHARE_CANCEL, this);
		}
	}

	@Override
	public void onComplete(Platform platf, int arg1,
			HashMap<String, Object> arg2) {
		Log.i("", "onComplete");
		if (arg1 == Platform.ACTION_SHARE) {
			UIHandler.sendEmptyMessage(SHARE_SUCCESS, this);
			Log.i("", "响应分享事件");
		}
		if (arg1 == Platform.SHARE_TEXT) {
			Log.i("", "响应分享文本事件");
			UIHandler.sendEmptyMessage(SHARE_SUCCESS, this);
			Log.i("", "..");
		}
	}

	@Override
	public void onError(Platform platf, int arg1, Throwable arg2) {
		// TODO Auto-generated method stub
		Log.i("", "onError");
		if (arg1 == Platform.ACTION_SHARE) {
			UIHandler.sendEmptyMessage(SHARE_ERROR, this);
		}
	}

	private final static int SHARE_SUCCESS = 1;
	private final static int SHARE_CANCEL = 2;
	private final static int SHARE_ERROR = 3;

	@Override
	public boolean handleMessage(Message msg) {
		Log.i("", "what = " + msg.what);
		switch (msg.what) {
		case SHARE_SUCCESS: {
			Log.i("", "arg1 = " + "分享成功");
			// Toast.makeText(MainActivity.getInstant(), "分享成功",
			// Toast.LENGTH_SHORT).show();
		}
			break;
		case SHARE_CANCEL: {
			Log.i("", "arg1 = " + "取消分享");
			Toast.makeText(MainActivity.getInstant(), "取消分享",
					Toast.LENGTH_SHORT).show();
		}
			break;
		case SHARE_ERROR: {
			Log.i("", "arg1 = " + "分享错误");
			Toast.makeText(MainActivity.getInstant(), "分享错误",
					Toast.LENGTH_SHORT).show();
		}
			break;
		}
		return false;
	}

}
